import React, {useState} from 'react'
import { Form, TreeSelect, Button, message, Input } from 'antd'
import { Store } from 'rc-field-form/lib/interface'
import { fetchRequest } from '../../../../../utils/Request'
import { url } from '../../../../../utils/url'
import { useRequest } from '@umijs/hooks'
import { useSelector } from 'react-redux'
import {useSingleState} from "nice-hooks";
import { getSecretString } from '../../../../../utils/encrypt';
import {any} from "prop-types";
interface RequestAddres {
    level: number,
    collegeId: string,
    collegeAreaId: string,
    building:string,
    unit:string,
    floor:string
}
export default function StartEntrance(props: any) {

    const [requestAddress,setRequestAddress] =useState<any>({"level": 0, "collegeId": "", "collegeAreaId": "","building":"","unit":"","floor":""})
    const [form] = Form.useForm()
    const [modifyAddressInfo, setmodifyAddressInfo] = useState<{  content: any }>({ content: null })
    const [state,setState]=useSingleState({isBlackCard:"",isCanApply:"",blaceCardCode:"",addressNode:any,phone:any});

    function onFinish(value: Store) {

        const params={phone:value.student_id}
        //第一步：验证手机号科道接口
        getBlackPhone.run(params)
       setState({phone:value.student_id})

    }


    const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 10 },
    };

    const tailLayout = {
        wrapperCol: { offset: 8, span: 10 },
    };

    //获取redux中的data
    const myData = useSelector((state: any) => {
        const data = state.deptManage.deptData
        disableSelect(data)
        return {
            deptData: data
        }
    })


    //递归修改item的key
    function disableSelect(arr: any[], ) {
        arr.map(item => {
            delete item.disabled
            item.key = item.deptID
            item.value = item.deptID
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }
    const getAllAddress = useRequest(getAllAddressNode, {
        manual: true,
        loadingDelay: 200
    })
    async function getAllAddressNode(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ADDRESS_NODE, params);
            if (json.success) {
                setState({addressNode:json.data})
                //获取地址正常才提交
                onSubmit.run(state.phone);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }
      //科道验证黑金星卡
    const getBlackPhone = useRequest(getBlackPhoneRequest, {
        manual: true,
        loadingDelay: 200
    })
    async function getBlackPhoneRequest(params: any) {
        try {
            const json = await fetchRequest(url.CHECK_BLACK_CARD_URL, params);
            console.log("科道返回数据")
            console.log(json)
            if (json.success) {
                setState({isBlackCard:json.isBlackCard,isCanApply:json.isCanApply})
                if(json.isBlackCard&&json.isCanApply)
                    setState({blaceCardCode:json.cardCode})
                //科道接口正常才获取地址
                getAllAddress.run(requestAddress)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    //信息提交的时候(获取该学号信息，如果已有门禁就提示不能新增)
    async function onSubmitInfo(value: any) {
        // console.log("提交的手机号")
        // console.log(value)
        const params={step:1,phone:getSecretString(value)}

        try {
            const json = await fetchRequest(url.APPLY_ENTRANCE, params);
            if (json.success) {
                if(state.isBlackCard && !state.isCanApply){
                    message.destroy();
                    message.error("卡资源异常,请先解决之后再申请!");
                    return;
                }
                // const params = { ...json,phone:state.phone,isBlackCard:state.isBlackCard,blackCard:state.blaceCardCode}
                const params = { ...json,...state}

                props.onVerifySuccess(params);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const onSubmit = useRequest(onSubmitInfo, {
        manual: true,
        loadingDelay: 200
    })

    return (
        <Form {...layout} form={form} onFinish={onFinish} initialValues={props.info === null ? undefined : { deptId: props.info.deptId, phone: props.info.phone }}>

            <Form.Item label="手机号" name="student_id" rules={[{ required: true, message: "必须要输入手机号" } ,{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' }]}>
                <Input placeholder="请输入手机号码"/>
            </Form.Item>
            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={onSubmit.loading}>下一步</Button>
            </Form.Item>
        </Form>
    )
}
